package com.ruoyi.web.controller.biz;

import com.alibaba.druid.support.json.JSONUtils;
import com.ruoyi.biz.domain.*;
import com.ruoyi.biz.service.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.service.ISysDictDataService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Stream;

/**
 * 课程导航
 *
 * @author fmi110
 * @date 2021-08-31
 */
@Controller
@RequestMapping("/biz/courseNav")
public class BizCourseNavController extends BaseController {
    private String prefix = "biz/courseNav";

    @Autowired
    private IBizCourseService bizCourseService;

    @Autowired
    private IBizSubjectService bizSubjectService;

    @Autowired
    private IBizCourseDetailService detailService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private IBizCourseExpertService bizCourseExpertService;

    @Autowired
    private IBizCourseExamService bizCourseExamService;

    @Autowired
    private IBizCourseMaterialLearnRecordService recordService;

    @GetMapping()
    public String course() {
        return prefix + "/course";
    }

    @GetMapping("/contentList/{id}")
    public String contentList(@PathVariable(value = "id") Long id, ModelMap mmap) {

        if (StringUtils.isNotNull(id)) {
            BizCourse course = bizCourseService.selectBizCourseById(id);

            String projectTypeLabel = dictDataService.selectDictLabel("course_project_type", course.getProjectType());
            course.setProjectTypeLabel(projectTypeLabel);
            mmap.put("course", course);

            Long userId = ShiroUtils.getUserId();
            HashMap<String, Object> param = new HashMap<>();
            param.put("userId", userId);
            param.put("courseId", id);

            BizCourseDetail detail = new BizCourseDetail();
            detail.setCourseId(id);
            List<BizCourseDetail> list = detailService.selectBizCourseDetailListWihtUserInfo(param);
            mmap.put("courseDetailList", list);
        }
        return prefix + "/contentList";
    }

    /**
     * 查询课程信息列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BizCourse bizCourse, ModelMap mmap) {
        startPage();
        List<BizCourse> list = bizCourseService.selectBizCourseList(bizCourse);
        return getDataTable(list);
    }

    /**
     * 选择学科管理树
     */
    @GetMapping(value = {"/selectManageTree/{id}", "/selectManageTree/"})
    public String selectManageTree(@PathVariable(value = "id", required = false) Long id, ModelMap mmap) {
        if (StringUtils.isNotNull(id)) {
            mmap.put("bizSubject", bizSubjectService.selectBizSubjectById(id));
        }
        return prefix + "/tree";
    }

    @GetMapping("/goLearn/{id}")
    public String goLearn(@PathVariable(value = "id") Long id, ModelMap mmap) {

        if (StringUtils.isNotNull(id)) {
            BizCourseDetail courseDetail = detailService.selectBizCourseDetailById(id);
            mmap.put("courseDetail", courseDetail);

            String teacherId = courseDetail.getTeacher();
            BizCourseExpert teacher = bizCourseExpertService.selectBizCourseExpertById(Long.valueOf(teacherId));
            mmap.put("teacher", teacher);

            Long userId = ShiroUtils.getUserId();
            int canExam = 0;
            if(userId!=null){
                BizCourseMaterialLearnRecord bizCourseMaterialLearnRecord = new BizCourseMaterialLearnRecord();
                bizCourseMaterialLearnRecord.setUserId(userId);
                bizCourseMaterialLearnRecord.setCourseDetailId(id);
                bizCourseMaterialLearnRecord.setDone(1);
                List<BizCourseMaterialLearnRecord> learnRecords = recordService.selectBizCourseMaterialLearnRecordList(bizCourseMaterialLearnRecord);
                if (!CollectionUtils.isEmpty(learnRecords)) {
                    canExam =1;
                }
            }
            mmap.put("canExam", canExam);

            if (StringUtils.isEmpty(courseDetail.getVideoUrl())) {
                String          pptUrl       = courseDetail.getPptUrl();
                if (StringUtils.isEmpty(pptUrl)) {
                    throw new BusinessException("资料未上传,请联系管理员上传");
                }
                String          maxStr      = pptUrl.substring(pptUrl.lastIndexOf("/") + 1).replace(".png", "");
                List<String> imgList = new ArrayList<>();
                for (int i = 1; i <= Integer.valueOf(maxStr); i++) {
                    imgList.add(courseDetail.getHost()+ pptUrl.replace(maxStr + ".png", i + ".png"));
                }
                if (CollectionUtils.isEmpty(imgList)) {
                    throw new BusinessException("资料未上传,请联系管理员上传");
                }
                mmap.put("courseDetail", courseDetail);
                mmap.put("imgList", imgList);
                mmap.put("total", maxStr);
                return prefix + "/ppt";
            }
        }

        return prefix + "/video";
    }

    @GetMapping("/ppt/{id}")
    public String ppt(@PathVariable(value = "id") Long id, ModelMap mmap) {

        if (StringUtils.isNotNull(id)) {
            BizCourseDetail courseDetail = detailService.selectBizCourseDetailById(id);

            String teacherId = courseDetail.getTeacher();
            BizCourseExpert teacher = bizCourseExpertService.selectBizCourseExpertById(Long.valueOf(teacherId));
            mmap.put("teacher", teacher);

            String          pptUrl       = courseDetail.getPptUrl();
            if (StringUtils.isEmpty(pptUrl)) {
                throw new BusinessException("资料未上传,请联系管理员上传");
            }
            String          maxStr      = pptUrl.substring(pptUrl.lastIndexOf("/") + 1).replace(".png", "");
            List<String> imgList = new ArrayList<>();
            for (int i = 1; i <= Integer.valueOf(maxStr); i++) {
                imgList.add(courseDetail.getHost()+ pptUrl.replace(maxStr + ".png", i + ".png"));
            }
            if (CollectionUtils.isEmpty(imgList)) {
                throw new BusinessException("资料未上传,请联系管理员上传");
            }
            mmap.put("courseDetail", courseDetail);
            mmap.put("imgList", imgList);
            mmap.put("total", maxStr);

            Long userId = ShiroUtils.getUserId();
            int canExam = 0;
            if(userId!=null){
                BizCourseMaterialLearnRecord bizCourseMaterialLearnRecord = new BizCourseMaterialLearnRecord();
                bizCourseMaterialLearnRecord.setUserId(userId);
                bizCourseMaterialLearnRecord.setCourseDetailId(id);
                bizCourseMaterialLearnRecord.setDone(1);
                List<BizCourseMaterialLearnRecord> learnRecords = recordService.selectBizCourseMaterialLearnRecordList(bizCourseMaterialLearnRecord);
                if (!CollectionUtils.isEmpty(learnRecords)) {
                    canExam =1;
                }
            }
            mmap.put("canExam", canExam);
        }
        return prefix + "/ppt";
    }

    @GetMapping("/exam/{id}")
    public String exam(@PathVariable(value = "id") Long id, ModelMap mmap) {

        BizCourseExam bizCourseExam = new BizCourseExam();
        bizCourseExam.setCourseDetailId(id);
        List<BizCourseExam> exams = bizCourseExamService.selectBizCourseExamList(bizCourseExam);
        if (CollectionUtils.isEmpty(exams)) {
            throw new BusinessException("课程未设置考试题");
        }
        bizCourseExam = exams.get(0);
        String examContent = bizCourseExam.getExamContent();
        if (!StringUtils.isEmpty(examContent)) {
            List<Map> List = (java.util.List<Map>) JSONUtils.parse(examContent);
            bizCourseExam.setExamList(List);
        }

        mmap.put("bizCourseExam", bizCourseExam);
        return prefix + "/exam";
    }

    @ResponseBody
    @PostMapping("/recordLearn")
    public AjaxResult recordLearn(BizCourseMaterialLearnRecord record) {
        Long userId = ShiroUtils.getUserId();
        if(userId!=null){
            BizCourseMaterialLearnRecord bizCourseMaterialLearnRecord = new BizCourseMaterialLearnRecord();
            bizCourseMaterialLearnRecord.setUserId(userId);
            bizCourseMaterialLearnRecord.setCourseDetailId(record.getCourseDetailId());
            bizCourseMaterialLearnRecord.setMaterialType(record.getMaterialType());
            List<BizCourseMaterialLearnRecord> learnRecords = recordService.selectBizCourseMaterialLearnRecordList(bizCourseMaterialLearnRecord);
            record.setUserId(userId);
            if (CollectionUtils.isEmpty(learnRecords)) {
                recordService.insertBizCourseMaterialLearnRecord(record);
            }else{
                recordService.updateBizCourseMaterialLearnRecord(record);
            }
        }else{
            return AjaxResult.error("用户id为空");
        }
        return AjaxResult.success();
    }

}
